package socket;

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

@SuppressWarnings("serial")
class SocketCliente extends JFrame
		 implements ActionListener {

   int port;
   String direction= null;
   JLabel text, clicked;
   JButton button;
   JPanel panel;
   JTextField textField;
   Socket socket = null;
   PrintWriter out = null;
   BufferedReader in = null;

   SocketCliente(String dir, int port){
	 this.port= port;
	 direction= dir;
     text = new JLabel("Texto enviado por el socket:");
     textField = new JTextField(20);
     button = new JButton("Hacer click");
     button.addActionListener(this);

     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", text);
     panel.add("Center", textField);
     panel.add("South", button);
   }

  public void actionPerformed(ActionEvent event){
     Object source = event.getSource();

     if(source == button){
//Se envian los datos
          String text = textField.getText();
          out.println(text);
	  textField.setText(new String(""));
//Se reciven
       try{
	  String line = in.readLine();
          System.out.println("Texto recivido :" + line);
       } catch (IOException e){
	 System.out.println("Fallo al leer");
       	 System.exit(1);
       }
     }
  }
  
  public void listenSocket(){
//Create socket connection
     try{
       socket = new Socket("", 5555);
       out = new PrintWriter(socket.getOutputStream(), true);
       in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     } catch (UnknownHostException e) {
       System.out.println("Destino deconocido: "+direction);
       System.exit(1);
     } catch  (IOException e) {
       System.out.println("No I/O");
       System.exit(1);
     }
  }

}
